import React, { useEffect, useState } from 'react'
import axios from 'axios';
import { useRequest } from 'ahooks';
import { message, Row, Col, Card, List } from 'antd';
import { PageHeader } from '@ant-design/pro-layout';
import { NavLink } from '_react-router-dom@6.3.0@react-router-dom';
import _ from 'lodash';
// 发起网络请求，游客系统访问新闻页面，要显示布状态（publishState===2）为 已发布 所有新闻信息,
const getTableDataSourceRequest = () => {
    return axios.get(`http://localhost:3000/news?_expand=category&publishState=2`)
};
export default function News() {
    // 表格数据源保存
    const [dataSource, setDataSource] = useState<any>([]);
    const { run: getTableDataSource, loading: getTableDataSourceLoading } = useRequest(getTableDataSourceRequest, {
        throttleWait: 300,
        manual: true,
        onSuccess: (result: any, params) => {
            if (result.status === 200) {
                console.log('我在执行', result.data);
                let categoryDataObj = _.groupBy(result.data, item => item.category.title);
                let categoryDataArray = [];
                for (let i in categoryDataObj) {
                    categoryDataArray.push({
                        type: i,
                        article: categoryDataObj[i]
                    })
                }
                console.log(categoryDataArray);
                setDataSource(categoryDataArray);
            }
        },
        onError(e, params) {
            message.warning('请求新闻数据失败');
        },
    });
    useEffect(() => {
        getTableDataSource();
    }, [])
    return (
        <div style={{ width: '95%', margin: '0 auto' }}>
            <PageHeader
                style={{ borderBottom: '1px solid rgb(235, 237, 240)', marginBottom: '20px' }}
                title='全球大新闻'
                subTitle='查看新闻'

            ></PageHeader>

            <Row gutter={[16, 16]}>
                {dataSource.map((item: any, index: number) =>
                    <Col span={8} key={index}>
                        <Card title={item.type} bordered={true} hoverable={true} style={{ height: '290px' }}>
                            <List
                                dataSource={item.article}
                                pagination={
                                    {
                                        pageSize: 2,
                                        hideOnSinglePage: true
                                    }
                                }
                                renderItem={(item2: any) => (
                                    <List.Item>
                                        <NavLink to={`/detail/${item2.id}`}>{item2.title}</NavLink>
                                    </List.Item>
                                )}
                            />
                        </Card>

                    </Col>
                )}
            </Row>
        </div>
    )
}
